import React, {useState, useRef, useEffect, useMemo} from 'react';
import {View, ScrollView} from 'react-native';
import {useTranslation} from 'react-i18next';
import {deviceApi} from '@/services/api/deviceApi';
import Toast from '@/utils/toast';
import {
  useAppTheme,
  Icon,
  TextInput,
  Switch,
  Button,
  Text,
  Cell,
} from 'tsun-smart-ui';
import Slider from '@react-native-community/slider';
import {BottomSheetModal} from '@gorhom/bottom-sheet';
import {ModelAction} from '@/components/ActionSheets';
import toast from '@/utils/toast';
import Clipboard from '@react-native-clipboard/clipboard';
import {BottomSheetTextInput} from '@gorhom/bottom-sheet';
import Logo from '@/components/Logo';
// 设备控制页面
const DeviceControl = ({
  route,
}: ReactNavigation.RootStackScreenProps<'DeviceControl'>) => {
  const {t} = useTranslation();
  const theme = useAppTheme();
  const bottomSheetModalRef = useRef<BottomSheetModal>(null);
  const {
    sn,
    deviceId,
    categoryName,
    moduleVersion,
    mac,
    state: {isConnect},
    iccId,
  } = route.params;
  useEffect(() => {
    toast.showLoading();
    deviceApi
      .getInverterState({deviceSn: sn})
      .then(({data: {ratePower, shutdown, ratePowerReal}}) => {
        setRatePower(ratePower!);
        setRatePowerReal((ratePowerReal ?? '--') + '');
        setCurrentPower((ratePowerReal ?? '0') + '');
        setRemoteShutdownEnabled(shutdown === 0 ? true : false);
      })
      .finally(() => {
        toast.hideLoading();
      });
  }, []);
  const [currentPower, setCurrentPower] = useState<string>('');
  const [remoteShutdownEnabled, setRemoteShutdownEnabled] = useState(false);
  const [loading, setLoading] = useState(false);
  const [ratePower, setRatePower] = useState(0);
  const [ratePowerReal, setRatePowerReal] = useState('');
  const [powerLoading, setPowerLoading] = useState(false);
  const handleRemoteShutdownToggle = async (value: boolean) => {
    try {
      setLoading(true);
      // 调用API设置设备参数
      const {data: success} = await deviceApi.setEquipmentParams({
        deviceSn: sn,
        shutdown: value ? 0 : 1,
        ratePower: null,
        ratePowerFactor: null,
        ratePowerReal: null,
      });
      if (success) {
        setRemoteShutdownEnabled(!remoteShutdownEnabled);
        Toast.success({
          message: t('common.operationSuccess', {defaultValue: '操作成功'}),
        });
      } else {
        throw new Error('Operation failed');
      }
    } finally {
      setLoading(false);
    }
  };
  const cellData = useMemo(() => {
    const result = [
      {
        title: t('device.model', {defaultValue: '设备型号'}),
        right: <Text>{categoryName}</Text>,
      },
      {
        title: t('upgrade.softwareVersion', {defaultValue: '软件版本'}),
        right: <Text>{moduleVersion}</Text>,
      },
      {
        title: t('syslog.MACaddr', {defaultValue: 'MAC 地址'}),
        right: <Text>{mac}</Text>,
      },
      {
        right: <Text>{deviceId}</Text>,
        title: t('userSetting.device.id', {defaultValue: '设备ID'}),
      },
    ];
    if (iccId) {
      result.push({
        title: t('userSetting.device.iccid', {defaultValue: 'ICCID'}),
        right: (
          <View className="flex-row items-center gap-x-2">
            <Text>{iccId}</Text>
            <Icon
              onPress={() => {
                Clipboard.setString(iccId);
                toast.showToast({
                  message: t('layout.copyTextSuccess'),
                });
              }}
              name="copy"
              size={16}
              color={theme.colors?.brand?.primary}></Icon>
          </View>
        ),
      });
    }
    return result;
  }, []);
  const handleSave = async () => {
    try {
      if (+currentPower > ratePower) {
        return toast.error({
          message: t('common.content.tip'),
        });
      }
      setPowerLoading(true);
      // 调用API设置设备参数
      const {data: success} = await deviceApi.setEquipmentParams({
        deviceSn: sn,
        shutdown: null,
        ratePower: ratePower,
        ratePowerFactor: 1,
        ratePowerReal: +currentPower,
      });
      if (success) {
        Toast.success({
          message: t('userSetting.saveSuccess', {defaultValue: '操作成功'}),
        });
        bottomSheetModalRef.current?.dismiss();
        setRatePowerReal(currentPower);
      } else {
        throw new Error('Operation failed');
      }
    } finally {
      setPowerLoading(false);
    }
  };
  return (
    <>
      <ScrollView
        contentContainerStyle={{
          padding: 16,
        }}>
        {/* 基本设置 */}
        <View className="mb-4">
          <Text
            className=" mb-2"
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            {t('common.general')}
          </Text>
          <Cell
            size="large"
            data={[
              {
                title: t('user.power_regulation', {defaultValue: '功率调节'}),
                description: t('user.device.adjustOutputPower'),
                left: size => <Logo name="power-change" size={24} containerSize={size} backgroundColor={theme.colors?.brand?.primaryLight!} color={theme.colors?.brand?.primary!} />,
                right: (
                  <View className="flex-row items-center justify-end gap-x-2 ml-2 min-w-16">
                    <Text>{ratePowerReal + 'W'}</Text>
                    <Icon
                      name="right"
                      size={10}
                      color={theme.colors?.neutral?.primary}></Icon>
                  </View>
                ),
                onPress() {
                  if (isConnect) {
                    setCurrentPower(
                      ratePowerReal === '--' ? '0' : ratePowerReal,
                    );
                    bottomSheetModalRef.current?.present();
                  }
                },
              },
              {
                title: t('user.remote_power_on_off'),
                description: t('user.device.remotelyControl'),
                left: size => <Logo name="ctrl" size={24} containerSize={size} backgroundColor={theme.colors?.brand?.primaryLight!} color={theme.colors?.brand?.primary!} />,
                right: (
                  <Switch
                    value={remoteShutdownEnabled}
                    loading={loading}
                    disabled={!isConnect || loading}
                    onValueChange={handleRemoteShutdownToggle}></Switch>
                ),
              },
            ]}></Cell>
        </View>

        {/* 设备信息 */}
        <View className="mb-4">
          <Text
            className=" mb-2"
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            {t('device.info', {defaultValue: '设备信息'})}
          </Text>
          <Cell size="large" data={cellData}></Cell>
        </View>
      </ScrollView>
      <ModelAction height={285} ref={bottomSheetModalRef}>
        <View className="mt-5  px-4">
          <View className="flex-row flex-center w-full">
            <Text className="flex-1" variant="bodyStrong">
              {t('user.power_regulation')}
            </Text>
            <View className="flex-row items-center gap-x-3">
              <View className='w-20 h-10 rounded flex-center' style={{
                backgroundColor:theme.colors?.background?.primary
              }}>
                <BottomSheetTextInput
                  value={currentPower}
                  style={{
                    paddingHorizontal:16,
                    width:'100%',
                    height:'100%',
                    paddingVertical:10,
                  }}
                  onChangeText={setCurrentPower}
                  keyboardType="numeric"
                  maxLength={4}
                />
              </View>
              <Text variant="bodyStrong">W</Text>
            </View>
          </View>
          <Slider
            style={{width: '100%', height: 40}}
            minimumValue={0}
            maximumValue={ratePower}
            value={+currentPower}
            onValueChange={value => {
              setCurrentPower(value.toFixed(0));
            }}
            step={100}
            minimumTrackTintColor={theme.colors?.brand?.primary}
            maximumTrackTintColor={theme.colors?.border?.primary}
          />
          <View className="flex-row flex-between">
            <Text>0</Text>
            <Text>{ratePower}</Text>
          </View>
          <Text
            className="mt-3"
            variant="caption"
            style={{
              color: theme.colors?.neutral?.secondaryTitle,
            }}>
            {t('message.text')}
          </Text>
          <View className="flex-row justify-between mt-[37] gap-x-3">
            <Button
              className="flex-1"
              variant="outline"
              style={{
                backgroundColor: theme.colors?.background?.primary,
              }}
              textStyle={{
                color: theme.colors?.neutral?.title,
              }}
              onPress={() => {
                bottomSheetModalRef.current?.dismiss();
              }}
              title={t('user.logOutCancel')}></Button>
            <Button
              onPress={handleSave}
              className="flex-1"
              loading={powerLoading}
              title={t('userSetting.save')}
              disabled={powerLoading}></Button>
          </View>
        </View>
      </ModelAction>
    </>
  );
};

export default DeviceControl;
